﻿using Donal.Xms.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Donal.Xms.Web.temp.main
{
    public partial class specifications : Web.UI.BasePage
    {
        private string discount_remark = "";
        private string action = "";
        private string _temp_action = "";
        private int id = 0;
        private Web.UI.UserPage userPage = new UI.UserPage();
        Dictionary<string, string> dicGoodsDtTitles = new Dictionary<string, string>();

        protected Model.products productsModel;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[DTKeys.SESSION_PRODUCTS] != null)
            {
                productsModel = (Model.products)Session[DTKeys.SESSION_PRODUCTS];
            }

            action = Session[DTKeys.SESSION_PRODUCTS_ACTIONS] != null ? Session[DTKeys.SESSION_PRODUCTS_ACTIONS].ToString() : "";
            id = DTRequest.GetQueryInt("id");

            RptBind();
        }

        #region 数据绑定=================================
        private void RptBind()
        {
            if (productsModel == null)
            {
                productsModel = new BLL.products().GetModel(id);
                if (productsModel == null)
                {
                    string url = "/index.html"; // 你希望父页面跳转到的URL
                    string js = "<script>window.parent.location.href='" + url + "';</script>";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "RedirectParent", js);
                    return;
                }
                else
                {
                    Session[DTKeys.SESSION_PRODUCTS] = productsModel;
                }
            }

            List<Model.products_attribute_field> fields = new BLL.products_attribute_field().GetDisplayList(productsModel.id, "S.display=0", "S.sort_id,S.id");

            if (fields == null)
            {
                string url = "/index.html"; // 你希望父页面跳转到的URL
                string js = "<script>window.parent.location.href='" + url + "';</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "RedirectParent", js);
                return;
            }

            Model.products_category productsCategoryModel = new BLL.products_category().GetModel(productsModel.category_id);
            if (productsCategoryModel == null)
            {
                string url = "/index.html"; // 你希望父页面跳转到的URL
                string js = "<script>window.parent.location.href='" + url + "';</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "RedirectParent", js);
                return;
            }

            DataTable goodsDt = new DataTable();

            if (productsModel.products_goods != null && productsModel.products_goods.Count > 0)
            {
                goodsDt.Columns.Add("id");
                goodsDt.Columns.Add("index"); dicGoodsDtTitles.Add("index", "序号");
                goodsDt.Columns.Add("title"); dicGoodsDtTitles.Add("title", "产品名称");

                foreach (Model.products_attribute_field f in fields)
                {
                    goodsDt.Columns.Add(f.name); dicGoodsDtTitles.Add(f.name, f.title);
                }

                goodsDt.Columns.Add("sell_price"); dicGoodsDtTitles.Add("sell_price", "含税单价");
            }

            int index = 0;
            foreach (Model.products_goods pg in productsModel.products_goods)
            {
                DataRow dr = goodsDt.NewRow();
                dr["id"] = pg.id;
                dr["index"] = ++index;
                dr["title"] = pg.title;

                foreach (Model.products_goods_filed pgf in pg.fields)
                {
                    if (goodsDt.Columns.Contains(pgf.field_name))//如果扩展字段在显示的列表中
                    {
                        dr[pgf.field_name] = pgf.field_value;
                    }
                }

                dr["sell_price"] = userPage.GetSpecPrice(pg.id, pg.title, pg.products_id, productsModel.title, productsModel.category_id, productsCategoryModel.title, pg.sell_price, out discount_remark);
                goodsDt.Rows.Add(dr);
            }

            // 创建表头行
            HtmlTableRow htmlTrHeader = new HtmlTableRow();
            // 创建数据选择行
            HtmlTableRow htmlTrDataSelector = new HtmlTableRow();


            // 遍历字典，创建表头和行
            foreach (KeyValuePair<string, string> kvp in dicGoodsDtTitles)
            {
                HtmlTableCell htmlTh = new HtmlTableCell("th");
                if (kvp.Key == "index")
                {
                    htmlTh.Attributes["rowspan"] = "2";
                }
                else
                {
                    HtmlTableCell htmlTd = new HtmlTableCell("td");
                    htmlTd.Attributes["style"] = "text-align: center;";

                    DropDownList ddl = new DropDownList();
                    ddl.ID = "ddl_" + kvp.Key;
                    ddl.AutoPostBack = true;
                    ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);

                    htmlTd.Controls.Add(ddl);
                    htmlTrDataSelector.Controls.Add(htmlTd);
                }
                htmlTh.Attributes["style"] = "width: 10%;";
                htmlTh.InnerText = kvp.Value;
                htmlTrHeader.Controls.Add(htmlTh);
            }


            HtmlTableCell htmlThQuantity = new HtmlTableCell("th");
            htmlThQuantity.Attributes["style"] = "width: 10%;";
            htmlThQuantity.Attributes["rowspan"] = "2";
            htmlThQuantity.InnerText = "订购数量";
            htmlTrHeader.Controls.Add(htmlThQuantity);

            tableTemplate.Rows.Add(htmlTrHeader);
            tableTemplate.Rows.Add(htmlTrDataSelector);

            #region 将筛选条件都赋值
            if (Utils.CheckDataTable(goodsDt))
            {
                foreach (KeyValuePair<string, string> kvp in dicGoodsDtTitles)
                {
                    IniDropDownList(kvp.Key, goodsDt);
                }
            }
            #endregion

            DataView dv = goodsDt.DefaultView;

            #region 选择筛选条件
            _temp_action = DESEncrypt.Decrypt(action);

            if (_temp_action != "")
            {
                StringBuilder sbSql = new StringBuilder();

                string[] parameters = _temp_action.Split(',');
                if (parameters.Length == dicGoodsDtTitles.Count - 1)
                {
                    sbSql.Append(" id > 0 ");

                    foreach (string s in parameters)
                    {
                        string[] ss = s.Split('.');
                        if (ss.Length == 2)
                        {
                            if (dicGoodsDtTitles.ContainsKey(ss[0]))
                            {
                                DropDownList ddl = (DropDownList)FindControlRecursive(this, "ddl_" + ss[0]);
                                if (ddl != null)
                                {
                                    ddl.SelectedIndex = Utils.ObjToInt(ss[1]);
                                    if (ss[1] != "0")
                                    {
                                        sbSql.Append(" and " + ss[0] + " ='" + ddl.SelectedItem.Text + "'");
                                    }
                                }
                            }
                        }
                    }

                    // 应用筛选器
                    dv.RowFilter = sbSql.ToString();

                    // 应用排序规则（可选）
                    // dv.Sort = "YourColumnName1 ASC, YourColumnName2 DESC";                    
                }
            }

            #endregion

            #region 加载数据
            LoadData(dv);
            #endregion

        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="goodsDt"></param>
        private void LoadData(DataView dv)
        {
            DataTable goodsDt = dv.ToTable();
            int index = 1;
            foreach (DataRow dr in goodsDt.Rows)
            {
                dr["index"] = index++;
                // 创建数据行
                HtmlTableRow htmlTrDataList = new HtmlTableRow();
                HtmlTableCell htmlTd = new HtmlTableCell("td");
                foreach (DataColumn dc in goodsDt.Columns)
                {
                    if (dc.ColumnName == "id")
                    {
                        continue;
                    }
                    htmlTd = new HtmlTableCell("td");
                    htmlTd.Attributes["style"] = "text-align: center;";
                    htmlTd.InnerHtml = dr[dc.ColumnName].ToString();
                    htmlTrDataList.Controls.Add(htmlTd);
                }
                htmlTd = new HtmlTableCell("td");
                htmlTd.Attributes["style"] = "text-align: center;";
                // 创建一个input元素，注意属性之间使用等号连接
                HtmlInputText inputNumber = new HtmlInputText();
                inputNumber.Attributes["type"] = "number";
                inputNumber.Attributes["value"] = "0";
                inputNumber.Attributes["max"] = "999";
                inputNumber.Attributes["min"] = "0";
                inputNumber.Attributes["id"] = "number_" + dr["id"].ToString();

                // 将input控件添加到td中
                htmlTd.Controls.Add(inputNumber);
                htmlTrDataList.Controls.Add(htmlTd);

                tableTemplate.Controls.Add(htmlTrDataList);
            }
        }

        private void IniDropDownList(string columnName, DataTable dt)
        {
            // 获取该列的唯一值           
            var distinctValues = dt.AsEnumerable()
                            .Select(row => Convert.ToString(row[columnName]))
                            .Distinct()
                            .ToList();

            string ddlName = "ddl_" + columnName;
            DropDownList ddl = (DropDownList)FindControlRecursive(this, ddlName);

            if (ddl != null)
            {
                ddl.Items.Clear();
                ddl.Items.Add(new ListItem("全部", "0"));

                // 添加数据
                for (int i = 0; i < distinctValues.Count; i++)
                {
                    string fileTxt = distinctValues[i];

                    if (columnName == "sell_price")
                    {
                        ddl.Items.Add(new ListItem(fileTxt, fileTxt));
                    }
                    else
                    {
                        ddl.Items.Add(new ListItem(fileTxt, (i + 1).ToString()));
                    }

                }
            }
        }

        public Control FindControlRecursive(Control root, string id)
        {
            if (root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control found = FindControlRecursive(c, id);
                if (found != null)
                    return found;
            }

            return null;
        }

        #endregion

        private void Redirect()
        {
            if (dicGoodsDtTitles.Count > 0)
            {
                string RedirectUrl = "/specifications-" + id + ".html";
                string EncryptCodes = "";
                foreach (KeyValuePair<string, string> kvp in dicGoodsDtTitles)
                {
                    DropDownList ddl = (DropDownList)FindControlRecursive(this, "ddl_" + kvp.Key);
                    if (ddl != null)
                    {
                        EncryptCodes += kvp.Key + "." + ddl.SelectedIndex + ",";
                    }
                }
                if (EncryptCodes != "")
                {
                    Session[DTKeys.SESSION_PRODUCTS_ACTIONS] = DESEncrypt.Encrypt(EncryptCodes.Substring(0, EncryptCodes.Length - 1));
                    Response.Redirect(RedirectUrl);
                }
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            Redirect();
        }
    }
}